package com.example.shunsu.nas;

import cn.hutool.extra.ftp.FtpException;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.extra.ssh.Sftp;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

import java.util.List;

/**
 * 南京邮电NAS测试
 */
public class NASNjupt {
    public static final String NAS_IP = "10.22.191.194";
    public static final int NAS_PORT = 30022;
    public static final String NAS_USERNAME = "root";
    public static final String NAS_PASSWORD = "bjca*20230301";

    public static final String ROOT_PATH_NAS = "/opt/nas/zbcgtest/";

    /**
     *
     */
    public static void main(String[] args) throws JSchException {


        addFile("/202308");
//        listDir( "");

    }

    /**
     * 添加file
     */
    public static void addFile(String path) {
        Session sessionLinux = JschUtil.getSession(NAS_IP, NAS_PORT, NAS_USERNAME, NAS_PASSWORD);
        Sftp sftp = JschUtil.createSftp(sessionLinux);

        try {
            String directory = ROOT_PATH_NAS + path;

            sftpMkdir(sftp, directory);

            String wjml = "D:\\DATA\\Pictures\\QQ图片20220531154231.jpg";
            String destPath = directory + "20220531154231.jpg";
            System.out.println("写入的：" + destPath);
            sftp.put(wjml, destPath);

//            sftp.get("/opt/econtract/nas/202306QQ图片20220531154231.jpg","D:\\DATA\\Downloads\\上传用文档222.docx");
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            sftp.close();
        }

        sftp.close();
        System.out.println("over");
    }


    /**
     * 查询文件夹
     */
    public static void listDir(String path) {
        Session sessionLinux = JschUtil.getSession(NAS_IP, NAS_PORT, NAS_USERNAME, NAS_PASSWORD);
        Sftp sftp = JschUtil.createSftp(sessionLinux);

        String directory = ROOT_PATH_NAS + path;

        List<String> stringList = sftp.ls(directory);
        for (String s : stringList) {
            System.out.println(s);
        }
        sftp.close();
        System.out.println("over");
    }

    /**
     * 创建文件夹 ，添加是否存在的判断
     *
     * @param sftp
     * @param path
     */
    public static void sftpMkdir(Sftp sftp, String path) {
        ChannelSftp client = sftp.getClient();
        boolean isDir = true;
        try {
            SftpATTRS stat = client.stat(path);
        } catch (SftpException e) {
            if (e.getMessage().contains("No such file")) {
                // 文件不存在直接返回false
                isDir = false;
            } else {
                throw new FtpException(e);
            }
        }
        if (!isDir) {
            sftp.mkdir(path);
        }
    }

}
